//
//  GPMessageCell.m
//  GuaPi
//
//  Created by 陈华 on 2017/6/20.
//  Copyright © 2017年 Joanlove. All rights reserved.
//

#import "GPMessageCell.h"


@implementation GPMessageCell

- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
    if (self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]) {
        
        //设置UI
        [self setupUI];
    }
    return self;
}

#pragma mark - 设置UI
/**设置UI*/
- (void)setupUI
{
    //创建元素
    [self setupElement];
    
    //设置约束
    [self setupConstraint];
}

/**创建元素*/
- (void)setupElement
{
    //设置cell的属性
    self.contentView.backgroundColor = COLOR(241, 242, 246);
    self.backgroundColor = COLOR(241, 242, 246);
    self.selectionStyle = UITableViewCellSelectionStyleNone;
    
    self.translatesAutoresizingMaskIntoConstraints = NO;
    
    //内容背景图片
    UIView *contentBackground = [[UIView alloc]init];
    contentBackground.backgroundColor = [UIColor colorWithRed:249.0/255 green:249.0/255 blue:249.0/255 alpha:1];
    [self.contentView addSubview:contentBackground];
    self.contentBackground = contentBackground;
    
    //timeLabel
    UILabel *timeLabel = [[UILabel alloc]init];
    timeLabel.font = [UIFont systemFontOfSize:12.0];
    timeLabel.textAlignment = NSTextAlignmentCenter;
    timeLabel.text = @"10:24";
    [self.contentView addSubview:timeLabel];
    self.timeLabel = timeLabel;
    
    //iconView
    UIImageView *iconImageView = [[UIImageView alloc]init];
    iconImageView.image = [UIImage imageNamed:@"head_portrait_blue_small"];
    iconImageView.layer.cornerRadius = 22;
    iconImageView.layer.masksToBounds = YES;
    [self.contentView addSubview:iconImageView];
    self.iconImageView = iconImageView;
    
    //nickname
    UILabel *nicknameLabel = [[UILabel alloc]init];
    nicknameLabel.font = [UIFont systemFontOfSize:12.0];
    nicknameLabel.textAlignment = NSTextAlignmentCenter;
//    nicknameLabel.text = @"陈华";
    [self.contentView addSubview:nicknameLabel];
    self.nicknameLabel = nicknameLabel;
    
    //消息发送中指示器
    UIActivityIndicatorView *sendingIndicatorView = [[UIActivityIndicatorView alloc]initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
    sendingIndicatorView.hidesWhenStopped = YES;
    [self.contentView addSubview:sendingIndicatorView];
    self.sendingIndicatorView = sendingIndicatorView;
    
    //消息发送失败icon
    UIImageView *sendFailIcon = [[UIImageView alloc]init];
    sendFailIcon.image = [UIImage imageNamed:@"ic_send_fail"];
    sendFailIcon.backgroundColor = [UIColor redColor];
    sendFailIcon.userInteractionEnabled = YES;
    sendFailIcon.layer.cornerRadius = 11;
    sendFailIcon.layer.masksToBounds = YES;
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapSendFaileIcon)];
    [sendFailIcon addGestureRecognizer:tap];
    [self.contentView addSubview:sendFailIcon];
    self.sendFaildIcon = sendFailIcon;
}

/**设置约束*/
- (void)setupConstraint
{
    //时间label
    [self.timeLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.contentView.mas_left);
        make.right.mas_equalTo(self.contentView.mas_right);
        make.top.mas_equalTo(self.contentView.mas_top).offset(10);
        make.height.mas_equalTo(20);
    }];
}


#pragma mark - 事件监听
/**点击发送失败图标后的事件监听*/
- (void)tapSendFaileIcon
{
    if ([self.delegate respondsToSelector:@selector(messageCell:didFailedIconClicked:)]) {
        [self.delegate messageCell:self didFailedIconClicked:self.message];
    }
}

- (void)setMessage:(GPMessageItem *)message
{
    _message = message;
    
    //赋值
    [self gp_updateValue:message];
    
    //更新约束
    [self gp_updateConstraint:message];
}

#pragma mark - 私有方法
/**赋值*/
- (void)gp_updateValue:(GPMessageItem *)message
{
    //更新时间
    self.timeLabel.text = message.displayTime;
    self.timeLabel.hidden = !message.isDisplayTime;
    
    //群成员昵称
    self.nicknameLabel.text = message.messageType == EMChatTypeChat?@"":(message.isSender?@"":message.nickname);
    
    //头像
    NSString *url = [KGetImageURL stringByAppendingPathComponent:message.avatarURLPath];
    [self.iconImageView sd_setImageWithURL:[NSURL URLWithString:url] placeholderImage:[UIImage imageNamed:@"head_portrait_blue_small"]];
    
    //消息发送指示器
    switch (message.messageStatus) {
        case EMMessageStatusDelivering:
        {
            //消息正在发送
            [self.sendingIndicatorView startAnimating];
            WEAKSELF
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [weakSelf.sendingIndicatorView stopAnimating];
            });
        }
            break;
        default:
            [self.sendingIndicatorView stopAnimating];
            break;
    }
    
    //发送失败标识
    switch (message.messageStatus) {
        case EMMessageStatusFailed:
            self.sendFaildIcon.hidden = NO;
            break;
            
        default:
            self.sendFaildIcon.hidden = YES;
            break;
    }
    
    //更新背景图片
    if (message.isSender) {
        self.contentBackground.backgroundColor = COLOR(95, 109, 215);
    }else{
        self.contentBackground.backgroundColor = [UIColor whiteColor];
    }
    
}

/**更新约束*/
- (void)gp_updateConstraint:(GPMessageItem *)message
{
    //如果是本人发送的
    if (message.isSender) {
        [self.iconImageView mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.right.mas_equalTo(self.contentView.mas_right).offset(-10);
            make.top.mas_equalTo(self.timeLabel.mas_bottom).offset(10);
            make.width.mas_equalTo(43);
            make.height.mas_equalTo(43);
        }];
        [self.nicknameLabel mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.right.mas_equalTo(self.iconImageView.mas_left).offset(-10);
            make.top.mas_equalTo(self.iconImageView.mas_top);
            make.height.mas_equalTo(0); //高度为0，隐藏掉
        }];
        [self.contentBackground mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.top.mas_equalTo(self.nicknameLabel.mas_bottom).offset(3);
            make.right.mas_equalTo(self.iconImageView.mas_left);
        }];
        [self.sendingIndicatorView mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.right.mas_equalTo(self.contentBackground.mas_left).offset(-5);
            make.centerY.mas_equalTo(self.contentBackground.mas_centerY);
        }];
        [self.sendFaildIcon mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.right.mas_equalTo(self.contentBackground.mas_left).offset(-5);
            make.centerY.mas_equalTo(self.contentBackground.mas_centerY);
            make.width.height.mas_equalTo(8);
        }];
    }
    //如果是对方发的
    else{
        
        [self.iconImageView mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_equalTo(self.contentView.mas_left).offset(10);
            make.top.mas_equalTo(self.timeLabel.mas_bottom).offset(10);
            make.width.mas_equalTo(43);
            make.height.mas_equalTo(43);
        }];
        [self.nicknameLabel mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_equalTo(self.iconImageView.mas_right).offset(10);
            make.top.mas_equalTo(self.iconImageView.mas_top);
        }];
        [self.contentBackground mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_equalTo(self.iconImageView.mas_right);
            make.top.mas_equalTo(self.nicknameLabel.mas_bottom).offset(3);
        }];
        [self.sendingIndicatorView mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_equalTo(self.contentBackground.mas_right).offset(5);
            make.centerY.mas_equalTo(self.contentBackground.mas_centerY);
        }];
        [self.sendFaildIcon mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_equalTo(self.contentBackground.mas_right).offset(5);
            make.centerY.mas_equalTo(self.contentBackground.mas_centerY);
            make.width.height.mas_equalTo(8);
        }];
        
    }
    
    //根据时间标签的显示与否来更新头像居上边缘的距离
    CGFloat marginTop = message.isDisplayTime?10:-30;
    [self.iconImageView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.timeLabel.mas_bottom).offset(marginTop);
    }];
    
    //更新
    [self layoutIfNeeded];
}

- (void)layoutSubviews
{
    [super layoutSubviews];
    
    
    //图片自定义圆角
    if (self.message.bodyType == EMMessageBodyTypeImage || self.message.bodyType == EMMessageBodyTypeLocation) {
        return;
    }
    
    if (self.message.isSender) {
        
        UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:self.contentBackground.bounds byRoundingCorners:UIRectCornerTopLeft|UIRectCornerBottomLeft|UIRectCornerBottomRight cornerRadii:CGSizeMake(self.contentBackground.bounds.size.height * 0.3, self.contentBackground.bounds.size.height * 0.3)];
        CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
        maskLayer.frame = self.contentBackground.bounds;
        maskLayer.path = maskPath.CGPath;
        self.contentBackground.layer.mask = maskLayer;

        
        
    }else{
        
        UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:self.contentBackground.bounds byRoundingCorners:UIRectCornerBottomRight | UIRectCornerTopRight | UIRectCornerBottomLeft cornerRadii:CGSizeMake(self.contentBackground.bounds.size.height * 0.3, self.contentBackground.bounds.size.height * 0.3)];
        CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
        maskLayer.frame = self.contentBackground.bounds;
        maskLayer.path = maskPath.CGPath;
        self.contentBackground.layer.mask = maskLayer;
        
    }
}



#pragma mark - 工具方法
+ (Class)cellClassWithMessage:(GPMessageItem *)message
{
    //取出消息体类型
    EMMessageBodyType type = message.bodyType;
    
    NSString *className = @"GPTextMessageCell";
    
    switch (type) {
        case EMMessageBodyTypeText:
        {
            className = @"GPTextMessageCell";
        }
            break;
        case EMMessageBodyTypeImage:
        {
            if (!message.isSosMsg) {
                className = @"GPImageMessageCell";
            }else{
                className = @"GPSOSMessageCell";
            }
        }
            break;
        case EMMessageBodyTypeLocation:
        {
            className = @"GPLocationMessageCell";
        }
            break;
            
        case EMMessageBodyTypeVoice:
        {
            className = @"GPVoiceMessageCell";
        }
            break;
        default:
        {
            className = @"GPTextMessageCell";
        }
            break;
    }
    
    return NSClassFromString(className);
}

+ (NSString *)reuseIdWithMessage:(GPMessageItem *)message
{
    //取出消息体类型
    EMMessageBodyType type = message.bodyType;
    
    NSString *Id = @"GPTextMessageCell";
    
    switch (type) {
        case EMMessageBodyTypeText:
        {
            Id = @"GPTextMessageCell";
        }
            break;
        case EMMessageBodyTypeImage:
        {
            if (!message.isSosMsg) {
                Id = @"GPImageMessageCell";
            }else{
                Id = @"GPSOSMessageCell";
            }
        }
            break;
            
        case EMMessageBodyTypeLocation:
        {
            Id = @"GPLocationMessageCell";
        }
            break;
            
        case EMMessageBodyTypeVoice:
        {
            Id = @"GPVoiceMessageCell";
        }
            break;
            
        default:
        {
            Id = @"GPTextMessageCell";
        }
            break;
    }
    
    return Id;
}

@end
